'use client';

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { useAuth } from '../contexts/AuthContext';
import Layout from '../components/Layout';
import { IconLoader2, IconHeartbeat, IconScale, IconApple, IconActivity, IconRefresh } from '@tabler/icons-react';

interface HealthStats {
  averageCalories: number;
  averageProtein: number;
  averageCarbs: number;
  averageFat: number;
  totalRecords: number;
  daysTracked: number;
}

interface HealthAdvice {
  generalAdvice: string;
  nutritionAdvice: string[];
  habitAdvice: string[];
  exerciseAdvice: string[];
}

// 添加缓存键常量
const CACHE_KEY = 'health-advice-cache';

export default function HealthAdvice() {
  const { user, loading: authLoading } = useAuth();
  const router = useRouter();
  const [loading, setLoading] = useState(true);
  const [regenerating, setRegenerating] = useState(false);
  const [stats, setStats] = useState<HealthStats | null>(null);
  const [advice, setAdvice] = useState<HealthAdvice | null>(null);

  // 从缓存加载建议
  const loadCachedAdvice = () => {
    const cached = localStorage.getItem(CACHE_KEY);
    if (cached) {
      try {
        const { advice: cachedAdvice, timestamp } = JSON.parse(cached);
        // 检查缓存是否在24小时内
        if (Date.now() - timestamp < 24 * 60 * 60 * 1000) {
          setAdvice(cachedAdvice);
          return true;
        }
      } catch (error) {
        console.error('解析缓存数据失败:', error);
      }
    }
    return false;
  };

  // 保存建议到缓存
  const saveAdviceToCache = (newAdvice: HealthAdvice) => {
    localStorage.setItem(CACHE_KEY, JSON.stringify({
      advice: newAdvice,
      timestamp: Date.now()
    }));
  };

  // 获取健康建议
  const fetchHealthAdvice = async () => {
    try {
      const res = await fetch('/api/health/advice', { credentials: 'include' });
      const data = await res.json();
      if (data.advice) {
        setAdvice(data.advice);
        saveAdviceToCache(data.advice);
      }
    } catch (error) {
      console.error('获取健康建议失败:', error);
    }
  };

  // 重新生成建议
  const handleRegenerateAdvice = async () => {
    setRegenerating(true);
    await fetchHealthAdvice();
    setRegenerating(false);
  };

  useEffect(() => {
    if (!authLoading && !user) {
      router.push('/login?redirect=/health-advice');
    }
  }, [user, authLoading, router]);

  useEffect(() => {
    if (user) {
      // 获取健康统计数据
      fetch('/api/health/stats', { credentials: 'include' })
        .then(res => res.json())
        .then(data => setStats(data.stats))
        .finally(() => setLoading(false));

      // 尝试从缓存加载建议
      const hasCache = loadCachedAdvice();
      if (!hasCache) {
        // 如果没有缓存，则从服务器获取
        fetchHealthAdvice();
      }
    }
  }, [user]);

  if (authLoading || !user) {
    return (
      <Layout>
        <div className="flex items-center justify-center min-h-screen">
          <IconLoader2 className="w-6 h-6 animate-spin text-blue-600" />
        </div>
      </Layout>
    );
  }

  return (
    <Layout>
      <div className="max-w-6xl mx-auto px-4 py-8">
        <div className="flex justify-between items-center mb-8">
          <h1 className="text-2xl font-bold">健康建议</h1>
          <button
            onClick={handleRegenerateAdvice}
            disabled={regenerating}
            className="btn-primary flex items-center gap-2"
          >
            <IconRefresh className={`w-5 h-5 ${regenerating ? 'animate-spin' : ''}`} />
            {regenerating ? '生成中...' : '重新生成建议'}
          </button>
        </div>

        {loading ? (
          <div className="flex justify-center py-8">
            <IconLoader2 className="w-6 h-6 animate-spin text-blue-600" />
          </div>
        ) : (
          <div className="space-y-8">
            {/* 健康统计概览 */}
            {stats && (
              <div className="bg-white rounded-lg shadow-sm p-6">
                <h2 className="text-lg font-semibold mb-4 flex items-center gap-2">
                  <IconHeartbeat className="w-5 h-5 text-red-500" />
                  健康数据概览
                </h2>
                <div className="grid md:grid-cols-4 gap-4">
                  <div className="bg-blue-50 rounded-lg p-4">
                    <div className="text-sm text-gray-600">平均热量摄入</div>
                    <div className="text-xl font-bold text-blue-600">
                      {stats.averageCalories.toFixed(0)} 千卡
                    </div>
                  </div>
                  <div className="bg-green-50 rounded-lg p-4">
                    <div className="text-sm text-gray-600">平均蛋白质</div>
                    <div className="text-xl font-bold text-green-600">
                      {stats.averageProtein.toFixed(1)}g
                    </div>
                  </div>
                  <div className="bg-yellow-50 rounded-lg p-4">
                    <div className="text-sm text-gray-600">平均碳水</div>
                    <div className="text-xl font-bold text-yellow-600">
                      {stats.averageCarbs.toFixed(1)}g
                    </div>
                  </div>
                  <div className="bg-red-50 rounded-lg p-4">
                    <div className="text-sm text-gray-600">平均脂肪</div>
                    <div className="text-xl font-bold text-red-600">
                      {stats.averageFat.toFixed(1)}g
                    </div>
                  </div>
                </div>
                <div className="mt-4 text-sm text-gray-600">
                  已记录 {stats.daysTracked} 天的饮食数据，共 {stats.totalRecords} 条记录
                </div>
              </div>
            )}

            {/* 健康建议 */}
            {advice && (
              <div className="space-y-6">
                {/* 总体建议 */}
                <div className="bg-white rounded-lg shadow-sm p-6">
                  <h2 className="text-lg font-semibold mb-4 flex items-center gap-2">
                    <IconScale className="w-5 h-5 text-blue-500" />
                    总体建议
                  </h2>
                  <p className="text-gray-600 whitespace-pre-line">{advice.generalAdvice}</p>
                </div>

                {/* 营养建议 */}
                <div className="bg-white rounded-lg shadow-sm p-6">
                  <h2 className="text-lg font-semibold mb-4 flex items-center gap-2">
                    <IconApple className="w-5 h-5 text-green-500" />
                    营养建议
                  </h2>
                  <ul className="space-y-2">
                    {advice.nutritionAdvice.map((item, index) => (
                      <li key={index} className="flex items-start gap-2">
                        <span className="text-green-500 font-bold">•</span>
                        <span className="text-gray-600">{item}</span>
                      </li>
                    ))}
                  </ul>
                </div>

                {/* 生活习惯建议 */}
                <div className="bg-white rounded-lg shadow-sm p-6">
                  <h2 className="text-lg font-semibold mb-4 flex items-center gap-2">
                    <IconActivity className="w-5 h-5 text-yellow-500" />
                    生活习惯建议
                  </h2>
                  <ul className="space-y-2">
                    {advice.habitAdvice.map((item, index) => (
                      <li key={index} className="flex items-start gap-2">
                        <span className="text-yellow-500 font-bold">•</span>
                        <span className="text-gray-600">{item}</span>
                      </li>
                    ))}
                  </ul>
                </div>

                {/* 运动建议 */}
                <div className="bg-white rounded-lg shadow-sm p-6">
                  <h2 className="text-lg font-semibold mb-4 flex items-center gap-2">
                    <IconActivity className="w-5 h-5 text-red-500" />
                    运动建议
                  </h2>
                  <ul className="space-y-2">
                    {advice.exerciseAdvice.map((item, index) => (
                      <li key={index} className="flex items-start gap-2">
                        <span className="text-red-500 font-bold">•</span>
                        <span className="text-gray-600">{item}</span>
                      </li>
                    ))}
                  </ul>
                </div>
              </div>
            )}
          </div>
        )}
      </div>
    </Layout>
  );
} 